<template>
  <view class="ai-chat-container">
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <template v-slot:content>AI 智能助手</template>
    </cu-custom>

    <!-- 聊天内容区 -->
    <scroll-view
      class="chat-scroll-view"
      scroll-y="true"
      :scroll-into-view="scrollTargetId"
      :scroll-with-animation="true"
    >
      <view class="chat-content">
        <!-- 欢迎消息 -->
        <view class="chat-item ai">
          <view class="avatar">
            <image src="/static/images/ai-customer.png" mode="aspectFill" />
          </view>
          <view class="message-bubble">
            <text>你好！有什么可以帮助你的吗？</text>
          </view>
        </view>

        <!-- 循环渲染消息 -->
        <view
          v-for="(message, index) in messages"
          :key="index"
          class="chat-item"
          :class="message.role"
        >
          <view class="avatar">
            <image
              :src="
                message.role === 'user'
                  ? '/static/images/user-avatar.png'
                  : '/static/images/ai-customer.png'
              "
              mode="aspectFill"
            />
          </view>
          <view class="message-bubble">
            <text>{{ message.content }}</text>
          </view>
        </view>

        <!-- AI正在输入... -->
        <view v-if="isLoading" class="chat-item ai">
          <view class="avatar">
            <image src="/static/images/ai-customer.png" mode="aspectFill" />
          </view>
          <view class="message-bubble is-loading">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
        </view>

        <!-- 滚动锚点 -->
        <view id="chat-anchor"></view>
      </view>
    </scroll-view>

    <!-- 底部输入区 -->
    <view class="chat-input-bar">
      <input
        v-model="inputText"
        class="input-field"
        type="text"
        placeholder="请输入您的问题..."
        @confirm="sendMessage"
        :disabled="isLoading"
      />
      <button
        class="send-btn cu-btn bg-gradual-blue round"
        @click="sendMessage"
        :disabled="isLoading || !inputText"
      >
        发送
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick } from "vue";

const messages = ref([]);
const inputText = ref("");
const isLoading = ref(false);
const scrollTargetId = ref(""); // 用于 scroll-into-view

// 请确保这个 baseURL 与你后端服务地址一致
const baseURL = "http://localhost:8021";

// 自动滚动到底部
const scrollToBottom = () => {
  // 通过更新ID来触发滚动到锚点
  nextTick(() => {
    scrollTargetId.value = "chat-anchor";
  });
};

const sendMessage = async () => {
  const content = inputText.value.trim();
  if (!content || isLoading.value) return;

  const userInput = inputText.value;
  messages.value.push({ role: "user", content: userInput });
  inputText.value = "";
  scrollToBottom();

  // 1. 只显示加载指示器，不再创建空消息
  isLoading.value = true;
  scrollToBottom();

  // #ifdef H5
  // 使用 fetch API 处理 POST 流式响应
  let isFirstChunk = true; // 标记是否为第一个数据块
  try {
    const response = await fetch(`${baseURL}/ai/chat`, {
      method: "POST",
      headers: {
        "Content-Type": "text/plain;charset=utf-8",
        Accept: "text/event-stream",
      },
      body: userInput,
    });

    if (!response.ok) throw new Error(`服务器错误: ${response.status}`);

    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let buffer = "";

    // 循环读取数据流
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() || "";

      for (const line of lines) {
        if (line.startsWith("data:")) {
          const data = line.substring(5).trim();

          if (data === "[DONE]") {
            reader.cancel();
            return;
          }

          if (isFirstChunk) {
            // 2. 收到第一个数据块时，隐藏加载并创建新消息
            isLoading.value = false;
            messages.value.push({ role: "ai", content: data });
            isFirstChunk = false;
          } else {
            // 3. 后续数据块，直接追加
            messages.value[messages.value.length - 1].content += data;
          }
          scrollToBottom();
        }
      }
    }
  } catch (error) {
    // 如果出错，确保加载状态被关闭
    if (isLoading.value) {
      isLoading.value = false;
      messages.value.push({
        role: "ai",
        content: "请求失败，请检查网络或后台服务。",
      });
    } else {
      messages.value[messages.value.length - 1].content += "\n[服务中断]";
    }
    scrollToBottom();
  }
  // #endif

  // #ifndef H5
  // 非H5平台回退到普通POST请求
  try {
    const res = await uni.request({
      url: `${baseURL}/ai/chat`,
      method: "POST",
      data: userInput,
      header: { "Content-Type": "text/plain;charset=utf-8" },
    });

    // 收到响应后，隐藏加载
    isLoading.value = false;

    if (res.statusCode === 200 && res.data) {
      // 创建并填充消息
      messages.value.push({ role: "ai", content: res.data });
    } else {
      throw new Error("Server error");
    }
  } catch (error) {
    isLoading.value = false;
    messages.value.push({ role: "ai", content: "请求失败，请检查网络。" });
  }
  scrollToBottom();
  // #endif
};
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f4f6fa;
}

.chat-scroll-view {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 120rpx; /* 为输入框留出空间 */
}

.chat-content {
  padding: 20rpx;
}

.chat-item {
  display: flex;
  margin-bottom: 30rpx;
  max-width: 80%;
}

.chat-item .avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.chat-item .avatar image {
  width: 100%;
  height: 100%;
}

.chat-item .message-bubble {
  background-color: #ffffff;
  padding: 20rpx 25rpx;
  border-radius: 18rpx;
  margin-left: 20rpx;
  word-break: break-all;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  font-size: 30rpx;
}

/* 用户消息样式 */
.chat-item.user {
  flex-direction: row-reverse;
  margin-left: auto; /* 靠右对齐 */
}

.chat-item.user .message-bubble {
  margin-left: 0;
  margin-right: 20rpx;
  background: linear-gradient(135deg, #6e8efb 0%, #a777e3 100%);
  color: #fff;
}

/* AI消息样式 */
.chat-item.ai {
  margin-right: auto; /* 靠左对齐 */
}

/* 正在输入的动画 */
.message-bubble.is-loading {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 28rpx 25rpx;
}
.dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #a777e3;
  animation: bounce 1.4s infinite ease-in-out both;
}
.dot:nth-child(2) {
  animation-delay: -0.16s;
}
.dot:nth-child(3) {
  animation-delay: -0.32s;
}
@keyframes bounce {
  0%,
  80%,
  100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 底部输入栏 */
.chat-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.03);
  box-sizing: border-box;
}

.input-field {
  flex: 1;
  height: 80rpx;
  background-color: #f4f6fa;
  border-radius: 40rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.send-btn {
  margin-left: 20rpx;
  height: 80rpx;
  line-height: 80rpx;
}
</style>
